from yahoo.search.web import WebSearch
from Message import Message
from Conversation import Conversation

def SearchYahoo(searchString):
	try:
		srch = WebSearch(app_id="tooangel-wave")
		srch.query = '"' + searchString + '"'
		results = srch.parse_results()
		if results.total_results_available > 100000:
			return 1
		return 0
	except:
		return 0

def message(text):
	query = Message.gql("WHERE text = :1", text)
	message = query.get()
	if not message:
		message = Message()
		message.text = text
		message.value = SearchYahoo(text)
		message.put()
	return message

def conversation(parentText, message):
	query = Message.gql("WHERE text = :1", parentText)
	parent = query.get()
	if not parent:
		parent = Message()
		parent.text = parentText
		message.value = SearchYahoo(message.text)
		parent.put()
		
	query = Conversation.gql("WHERE father = :1 AND son = :2", parent, message)
	conversation = query.get()
	if conversation:
		conversation.value += 1
	else:
		conversation = Conversation()
		conversation.father = parent
		conversation.son = message
		conversation.value = 1
	conversation.put()	
